<template>
    <div class="mcp-config">
        <el-row :gutter="20">
            <el-col :span="24">
                <el-card class="box-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <h3>MCP列表</h3>
                        </div>
                    </template>
                    <div class="table-wrapper">
                        <el-table :data="mcps" style="width: 100%; table-layout: fixed;">
                            <el-table-column prop="Name" label="MCP名" width="140px"></el-table-column>
                            <el-table-column prop="McpType" label="mcp类型" width="80px"></el-table-column>
                            <el-table-column prop="Url" label="API 地址"></el-table-column>
                            <el-table-column label="操作" width="140px">
                                <template #default="{ $index }">
                                    <el-button size="small" @click="editMcp($index)">编辑</el-button>
                                    <el-button size="small" type="danger" @click="deleteMcp($index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>
            </el-col>

            <el-col :span="24">
                <el-card class="box-card" shadow="never">
                    <template #header>
                        <div class="card-header">
                            <h3>MCP配置</h3>
                            <div style="display: flex; gap: 10px;">
                                <el-button type="success" size="small" @click="resetForm()">新建</el-button>
                                <el-button type="primary" size="small" @click="saveMcp">保存</el-button>
                            </div>
                        </div>
                    </template>

                    <!-- 表单包裹在 tabs 中 -->
                    <el-form :model="form" label-width="140px" @submit.prevent="saveMcp">
                        <el-tabs v-model="activeTab" type="card">
                            <!-- 通用设置 -->
                            <el-tab-pane label="通用" name="general">
                                <!-- MCP名称 -->
                                <el-form-item label="MCP名称">
                                    <el-input v-model="form.Name" placeholder="自定义名称" />
                                </el-form-item>

                                <!-- MCP类型 -->
                                <el-form-item label="MCP类型">
                                    <el-select v-model="form.McpType" placeholder="请选择模型类型" style="width: 100%">
                                        <el-option label="标准输入输出 (stdio)" value="stdio" />
                                        <el-option label="SSE 流式通信" value="sse" />
                                    </el-select>
                                </el-form-item>

                                <!-- API 地址 -->
                                <el-form-item label="MCP URL">
                                    <el-input v-model="form.Url" placeholder="例如：http://localhost:11434" />
                                </el-form-item>
                            </el-tab-pane>

                            <!-- 提示词 -->
                            <el-tab-pane label="提示词" name="prompt" v-if="form.Prompts?.length">
                                <el-form-item label="系统提示词">
                                    <el-input v-model="form.Prompts" type="textarea" :rows="4" placeholder="请输入系统提示词" />
                                </el-form-item>

                            </el-tab-pane>

                            <!-- 工具 -->
                            <el-tab-pane label="工具" name="tools" v-if="form.Tools?.length">
                                <!-- 新增：工具信息展示列表 -->
                                <div class="tool-list scrollable-list">
                                    <el-card v-for="tool in form.Tools" :key="tool.name" class="tool-card">
                                        <div class="tool-header">
                                            <strong>{{ tool.name }}</strong>
                                        </div>
                                        <div class="tool-description">
                                            {{ tool.description }}
                                        </div>
                                    </el-card>
                                </div>
                            </el-tab-pane>

                            <!-- 资源 -->
                            <el-tab-pane label="资源" name="resources" v-if="form.Resources?.length">
                                <el-form-item label="关联资源">
                                    <el-select v-model="form.Resources" multiple placeholder="请选择关联资源"
                                        style="width: 100%">
                                        <el-option v-for="resource in availableResources" :key="resource.value"
                                            :label="resource.label" :value="resource.value" />
                                    </el-select>
                                </el-form-item>
                            </el-tab-pane>
                        </el-tabs>
                    </el-form>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script setup lang="ts" name="McpSettings">
import { ref, inject, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { McpType, FlowAPI } from '@/types/types';

const flowAPI = inject<FlowAPI>('flowAPI');
if (!flowAPI) {
    throw new Error('flowAPI 必须通过 provide 提供');
}

const isEditing = ref(false);
const currentEditIndex = ref<number | null>(null);

const mcps = ref<McpType[]>([]);

// 当前激活的 tab
const activeTab = ref('general');

// 可选工具列表（示例）
const availableTools = [
    { label: '知识库检索', value: 'knowledge_search' },
    { label: '代码解释器', value: 'code_interpreter' },
    { label: '图像生成', value: 'image_generator' }
];

// 可选资源列表（示例）
const availableResources = [
    { label: '项目文档', value: 'project_doc' },
    { label: 'API 文档', value: 'api_doc' },
    { label: '用户手册', value: 'user_guide' }
];

const saveMcp = () => {
    const newMcp = { ...form.value };
    if (!flowAPI.addMcp) {
        ElMessage.error('缺少保存MCP接口');
        return;
    }
    if (!flowAPI.getMcp) {
        ElMessage.error('缺少读取MCP接口');
        return;
    }

    if (newMcp.Name === '') {
        ElMessage.error('请填写MCP名称');
        return;
    }
    if (newMcp.McpType === '') {
        ElMessage.error('请选择mcp类型');
        return;
    }
    if (newMcp.Url === '') {
        ElMessage.error('请填写API地址');
        return;
    }
    flowAPI.addMcp(newMcp).then((res) => {
        if (res.code !== 200) {
            ElMessage.error('添加MCP失败');
            return;
        }
        newMcp.ID = res.data.id;

        if (currentEditIndex.value !== null) {
            mcps.value[currentEditIndex.value] = newMcp;
        } else {
            mcps.value.push(newMcp);
        }

        flowAPI.getMcp({
            "id": newMcp.ID
        }).then((res) => {
            form.value = res.data;
            ElMessage.success('添加MCP成功');
        })
    }).catch(() => {
        ElMessage.error('添加MCP失败');
    });
};

const deleteMcp = (index: number) => {
    if (!flowAPI.deleteMcp) {
        ElMessage.error('删除MCP失败');
        return;
    }
    const id = mcps.value[index].ID;
    flowAPI.deleteMcp({
        "id": id
    }).then(() => {
        ElMessage.success('删除MCP成功');
        mcps.value.splice(index, 1);
        if (id === form.value.ID) {
            resetForm();
        }
    }).catch(() => {
        ElMessage.error('删除MCP失败');
    });
};

const editMcp = (index: number) => {
    if (!flowAPI.getMcp) {
        ElMessage.error('缺少读取MCP接口');
        return;
    }
    flowAPI.getMcp({
        "id": mcps.value[index].ID
    }).then((res) => {
        if (res.code !== 200) {
            ElMessage.error('获取MCP失败');
            return;
        }

        form.value = res.data;
        isEditing.value = true;
        currentEditIndex.value = index;
    }).catch(() => {
        ElMessage.error('读取MCP失败');
    });
};

// 获取模型列表
const loadMcps = async () => {
    try {
        if (!flowAPI.getMcpList) {
            ElMessage.error('获取MCP列表失败');
            return;
        }
        const res = await flowAPI.getMcpList();
        if (res.code !== 200) {
            ElMessage.error('获取MCP列表失败');
            return;
        }
        if (Array.isArray(res.data)) {
            mcps.value = res.data;
        } else {
            mcps.value = [];
        }
    } catch (err) {
        ElMessage.error('加载MCP列表失败');
    }
};

onMounted(() => {
    loadMcps();
});

const resetForm = () => {
    form.value = {
        ID: 0,
        Name: '',
        McpType: 'sse',
        Url: '',
        Prompts: [],
        Tools: [],
        Resources: []
    };
    currentEditIndex.value = null;
};

const form = ref<McpType>({
    ID: 0,
    Name: '',
    McpType: 'sse',
    Url: '',
    Prompts: [],
    Tools: [],
    Resources: []
});
</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    font-weight: bold;
    color: #333;
}

.large-model-settings {
    padding: 20px;
    background-color: #f9f9f9;
}

.box-card {
    border-radius: 8px;
}

.table-wrapper {
    width: 70vw;
    height: 30vh;
    overflow: auto;
    position: relative;
}

.table-wrapper::-webkit-scrollbar {
    height: 12px;
}

/* 固定宽度滚动条占位 */
.table-wrapper::after {
    content: '';
    display: block;
    height: 12px;
    width: 100%;
    visibility: hidden;
    flex-shrink: 0;
}

.id-wrapper {
    /* 填充剩余空间 */
    flex: 1 1 auto;
    min-width: 400px;
    display: inline-block;
}

.id-text {
    width: 100%;
    padding: 6px 12px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    font-family: monospace;
    font-size: 13px;
    color: #666;
    box-sizing: border-box;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.custom-select-dropdown .el-select-dropdown__item {
    height: auto;
    white-space: normal;
    line-height: 1.5;
}

.custom-select-dropdown .el-select-dropdown {
    max-height: 400px;
    overflow: auto;
}

/* 自定义 tabs 样式 */
.el-tabs--card>.el-tabs__header {
    border-bottom: none;
    background-color: #f5f7fa;
    border-radius: 6px;
    padding: 0 10px;
}

.el-tabs--card>.el-tabs__header .el-tabs__nav {
    border: none;
    border-radius: 6px;
    overflow: hidden;
}

.el-tabs--card>.el-tabs__header .el-tabs__item {
    border: none;
    border-radius: 6px;
    background-color: #e4e7ed;
    margin-right: 8px;
    color: #666;
    transition: all 0.2s ease-in-out;
    padding: 10px 20px;
}

.el-tabs--card>.el-tabs__header .el-tabs__item.is-active {
    background-color: #409EFF;
    color: white;
    font-weight: bold;
}

.el-tabs--card>.el-tabs__header .el-tabs__item:hover {
    background-color: #d3dce6;
    color: #333;
}

/* 减少 tab 内容区域的上下边距 */
.el-tab-pane {
    padding: 15px 0;
}

.scrollable-list {
    max-height: 600px;
    /* 固定高度 */
    overflow-y: auto;
    /* 垂直滚动 */
    padding-right: 4px;
    /* 避免滚动条遮挡内容 */
}

/* 可选：美化滚动条（仅 Chrome 等 Webkit 浏览器） */
.scrollable-list::-webkit-scrollbar {
    width: 6px;
}

.scrollable-list::-webkit-scrollbar-track {
    background-color: #f1f1f1;
    border-radius: 3px;
}

.scrollable-list::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 3px;
}

.scrollable-list::-webkit-scrollbar-thumb:hover {
    background-color: #aaa;
}

.tool-card {
    background-color: #ffffff;
    border-radius: 8px;
    padding: 6px 10px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    transition: all 0.2s ease-in-out;
    margin-bottom: 10px;
}

.tool-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.tool-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.tool-header strong {
    font-size: 16px;
    font-weight: bold;
    color: #333;
}

.tool-description {
    font-size: 13px;
    line-height: 1.6;
    color: #666;
}
</style>